import db from '../mongo'
import { parseTime } from '../middleware/comFunc/formatTime'
let userSchema = db.Schema({
    username: {                         // 账户
      type:String,
      unique: true
    },
    pwd: {                          // 密码
      type: String,
      required: true
    },
    name: {                          // 密码
      type: String,
      required: true
    },
    avatar: {                          // 头像
      type: String,
      default: 'http://7xrgfl.com1.z0.glb.clouddn.com/'
                + 'FrgZ2d6bbj7Th1w3m7lD7cCLBcBj'
    },
    roles: {                           // 角色（默认user）
      type: Array,
      default: ['user']
    },

    createAtTime: {                        // 注册日期
      type: String,
      default: ''
    },

    lastLoginAtTime: {                     // 上次登录时间
      type: String,
      default: ''
    }
})

userSchema.pre('save', function (next) {
  if (this.isNew) {
    this.createAtTime = this.lastLoginAtTime = parseTime(Date.now())
  } else {
    this.lastLoginAtTime = Date.now()
  }
  next()
})
userSchema.pre('save', function (next) {
  this.update({},{ $set: { lastLoginAtTime: parseTime(Date.now()) } })
  next()
})

export default db.model('user', userSchema);
